package com.zls.controller;

import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

@RestController
@RequestMapping("test")
public class TestController {
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private RabbitTemplate.ConfirmCallback myConfirmCallback;
    @Autowired
    private RabbitTemplate.ReturnCallback myReturnCallback;

    /**
     * 发送消息
     *
     * @return
     */
    @RequestMapping("/send1")
    public String send1(){
        //设置回调函数
        rabbitTemplate.setConfirmCallback(myConfirmCallback);
        //发送信息
        rabbitTemplate.convertAndSend("exchange_direct_demo01", "item.insert", "hello insert");
        return "ok";
    }
    @RequestMapping("/send2")
    public String send2() {
        rabbitTemplate.setConfirmCallback(myConfirmCallback);
        //设置回调函数
        rabbitTemplate.setReturnCallback(myReturnCallback);
        //发送消息
        rabbitTemplate.convertAndSend("exchange_direct_demo01", "item.insert", "hello insert");
        return "ok";
    }
    @RequestMapping("/send3")
    public String send3() {
        //设置回调函数
        //发送消息
        rabbitTemplate.convertAndSend("exchange_direct_demo01", "item.insert", "hello insert");
        return "ok";
    }
    /**
     * 发送 ttl测试相关的消息
     * @return
     */
    @RequestMapping("/send4")
    public String send4() {
        //设置回调函数
        //发送消息
        rabbitTemplate.convertAndSend("exchange_direct_demo02", "item.ttl", "hello ttl哈哈");
        return "ok";
    }
    /**
     * 测试发送死信队列
     * @return
     */
    @RequestMapping("/send5")
    public String send5() {
        //设置回调函数
        //发送消息
        rabbitTemplate.convertAndSend("queue_demo03_deq", "hello dlx哈哈");
        return "ok";
    }
    /**
     * 发送下单
     *
     * @return
     */
    @RequestMapping("/send6")
    public String send6() {
        //发送消息到死信队列   可以使用默认的交换机 指定routingkey为死信队列名即可
        System.out.println("用户下单成功，10秒钟之后如果没有支付，则过期，回滚订单");
        System.out.println("时间："+new Date());
        rabbitTemplate.convertAndSend("queue_order_queue1", (Object) "哈哈我要检查你是否有支付",
                new MessagePostProcessor() {
                    @Override
                    public Message postProcessMessage(Message message) throws AmqpException {
                        message.getMessageProperties().setExpiration("10000");//设置该消息的过期时间
                        return message;
                    }
                });
        return "用户下单成功，10秒钟之后如果没有支付，则过期，回滚订单";
    }
}
